#!/usr/bin/env python
#
# Copyright 2008 Richard J. Bell. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

""" Base request handler """

# Python Imports
import os

# Google App Engine Imports
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.ext.webapp import template

# Application Imports

class GWRequestHandler(webapp.RequestHandler):
    """ GWRequestHandler extends webapp.RequestHandler by defining the 
        the generate method and rendering a Django template in response to 
        a web request.
  """
    def generate(self, templateName, templateValues={}):
        from app.gwconfig import DEBUG
        from app.gwuser import GWUser
        """ Generate renders an HTML template along with values passed to that 
            template
        Args:
        templateName, string: The name of the HTML template
        templateValues, dictionary: Values to use in the HTML template.
        """
        # Display the user name if available and the login/logout URL on all pages
        values = {'nickname': 'Not logged on.', 'user': 'Unknown', 'login': 'false', 'isAdmin': 'false', 'isDeveloper': 'false'}              # set the user information
        user, gwuser = GWUser.getUserInfo()
        if user:
            values['nickname'] = user.nickname()
            values['login'] = 'true'
        if gwuser:
            values['userkey'] = str(gwuser.key())
        if GWUser.isAdmin():
            values['isAdmin'] = 'true'
        if users.is_current_user_admin():
            values['isDeveloper'] = 'true'
        values.update(templateValues)                                           # add the template values
        # Construct the path to the template
        directory = os.path.dirname(__file__) + '/..'
        path = os.path.join(directory, 'templates', templateName)
        # Respond to the request by rendering the template
        self.response.out.write(template.render(path, values, debug=DEBUG))

